﻿using System;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using Lean.Touch;
using UnityEngine;

namespace IQIGame.Onigao.GamePlay
{
    public class BattleTouchController : BattleRenderBaseController
    {
        private Vector2 mTouchLastPos;
        private bool mDraging;
        // private bool mTouchDown;
        
        /// <summary>
        /// 记录非gui开始finger
        /// </summary>
        private HashSet<LeanFinger> noStartGuiTouchs = new HashSet<LeanFinger>();
        private List<LeanFinger> tempTouchs = new List<LeanFinger>();
        
        public override async UniTask Initialize(BattleRenderContrller rRenderCtrl)
        {
            await base.Initialize(rRenderCtrl);
            
            LeanTouch.OnGesture += OnTouch;
            LeanTouch.OnFingerTap += OnTouchEnd;
            LeanTouch.OnFingerUp += OnTouchEnd;
        }

        public override void Dispose()
        {
            base.Dispose();
            LeanTouch.OnGesture -= OnTouch;
            LeanTouch.OnFingerTap -= OnTouchEnd;
            LeanTouch.OnFingerUp -= OnTouchEnd;
        }

        public void OnTouch(List<LeanFinger> touchs)
        {
            this.tempTouchs.Clear();
            foreach (var f in touchs)
            {
                if (!f.StartedOverGui && !f.Up)
                {
                    this.tempTouchs.Add(f);
                    this.noStartGuiTouchs.Add(f);
                }
            }
            if (tempTouchs.Count == 0)
            {
                return;
            }
            var rTouch = this.tempTouchs[0];
            var vec2 = rTouch.ScreenPosition;
            if (this.mTouchLastPos == Vector2.zero)
            {
                this.mTouchLastPos = vec2;
            }
            var vec1 = this.mTouchLastPos;
            var rDelta = vec2 - vec1;
            if(!this.mDraging && Math.Abs(rDelta.x) + Math.Abs(rDelta.y) > 20)
            {
                this.mDraging = true;
            }
            else if(this.mDraging)
            {
                this.OnDrag(rDelta);
            }
            this.mTouchLastPos = vec2;
        }

        private void OnTouchEnd(LeanFinger touch)
        {
            var removed = this.noStartGuiTouchs.Remove(touch);
            if (removed && this.noStartGuiTouchs.Count == 0)
            {
                if (this.mDraging)
                {
                    this.OnDragEnd();
                    this.mDraging = false;
                }
                this.mTouchLastPos = Vector2.zero;
            }
        }
        
        private void OnDrag(Vector2 rDrag)
        {
           this.mCtrl.sceneCtrl.DragCamera(-rDrag);
        }

        private void OnDragEnd()
        {
            this.mDraging = false;
            this.mCtrl.sceneCtrl.ResetCamera();
        }
    }
}